var status = 0;
var statusGroup = 0;
function checkRebuildComplete(callback) {
	if (callback) {
		callback();
	}
	if (status == 1){
		setTimeout(function() {
			checkRebuildComplete(callback);
		}, 60000);
	}
}
function checkRebuildGroupComplete(callback) {
	if (callback) {
		callback();
	}
	if (statusGroup == 1){
		setTimeout(function() {
			checkRebuildGroupComplete(callback);
		}, 60000);
	}
}

jQuery(document).ready(function() {
	jQuery("#select-server").change(function(){
		jQuery("#select-server-form").submit();
	});
	jQuery("#close-button input").click(function(){
		jQuery.modal.close();
	});
	jQuery("#rebuild-button").click(function(){
		jQuery("#close-button").css("display", "none");
		jQuery('#basic-modal-content').modal();
		
		timeStamp = new Date().getTime();
		status = 1;
		jQuery.post("/index.php/cirpho/servers/rebuild", { max_width: jQuery("#max_width").val(), timeStamp: timeStamp },
			function(data) {
				//alert("Ok");		
		 	}
		);
		checkRebuildComplete(function(){
			jQuery(".error").css("display", "none");
			jQuery.post("/index.php/cirpho/servers/checkRebuild", {timeStamp: timeStamp },
				function(data) {
				//	alert(data);
					res = eval('(' + data + ')');
					if(res.complete && status != 0){
						status = 0;
						jQuery(".error").css("display", "none");
						jQuery("#rebuild-message").html("Rebuild completed successful!");
						jQuery("#close-button").css("display", "block");
					}
			 	}
			);
		});
		return false;
	});
	
	jQuery(".rebuild-group-front").click(function(){
		jQuery("#close-button input").css("display", "none");
		jQuery('#basic-modal-content').modal();
		
		timeStamp = new Date().getTime();
		gid = jQuery(this).attr('id');
		statusGroup = 1;
		jQuery.post("/index.php/cirpho/samples/rebuild", {gid: gid, max_width: jQuery("#max_width").val(), timeStamp: timeStamp },
			function(data) {
				//alert("Ok");		
		 	}
		);
		checkRebuildGroupComplete(function(){
			jQuery(".error").css("display", "none");
			jQuery.post("/index.php/cirpho/samples/checkRebuild", {timeStamp: timeStamp },
				function(data) {
					//alert(data);
					res = eval('(' + data + ')');
					if(res.complete && statusGroup != 0){
						statusGroup = 0;
						jQuery(".error").css("display", "none");
						jQuery("#rebuild-message").html("Rebuild completed successful!");
						jQuery("#close-button input").css("display", "block");
					}
			 	}
			);
		});
		return false;
	});
});
